var authStatus = '';
var userType = '';
var memberType = '';
var memberLevel = '';
var currentPage = 1;
var id1;

$(document).ready(function () {
    //外部js调用
    laydate({
        elem: '#startTime', //需显示日期的元素选择器
        event: 'focus', //触发事件
        format: 'YYYY-MM-DD hh:mm:ss', //日期格式
        istime: true, //是否开启时间选择
        isclear: true, //是否显示清空
        istoday: true, //是否显示今天
        issure: true, //是否显示确认
        festival: true, //是否显示节日
        min: '1900-01-01 00:00:00',//最小日期
        max: '2099-12-31 23:59:59',//最大日期
        start: laydate.now(),    //开始日期
        key: '2017-01-17 23:22:59'
        //choose: function(dates){} //选择好日期的回调
    });
    //外部js调用
    laydate({
        elem: '#endTime', //需显示日期的元素选择器
        event: 'focus', //触发事件
        format: 'YYYY-MM-DD hh:mm:ss', //日期格式
        istime: true, //是否开启时间选择
        isclear: true, //是否显示清空
        istoday: true, //是否显示今天
        issure: true, //是否显示确认
        festival: true, //是否显示节日
        min: '1900-01-01 00:00:00',//最小日期
        max: '2099-12-31 23:59:59',//最大日期
        start: laydate.now(),    //开始日期
        key: '2017-01-17 23:22:59'
        //choose: function(dates){} //选择好日期的回调
    });

    showPurchaseRate();
    init(currentPage, memberType, userType, "", memberLevel, callback);
})

//显示购买率、复购率
function showPurchaseRate(){
    $.ajax({
        url: urlcore + "/api/muser/calcuPurchaseFrequency",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {
                var cbdata=data.data;
                var geOneRate=(cbdata.geOneRate*100).toFixed(1)+"%";
                var geTwoRate=(cbdata.geTwoRate*100).toFixed(1)+"%";
                $("#geOneRate").val(geOneRate);
                $("#geTwoRate").val(geTwoRate);
            } else{
                alert(data.msg);
            }

        },error:function(data) {
            console.log("error")
        }
    });
}


function init(currentPage, memberType, userType, phoneNumber, memberLevel, callback) {
    $("#thislist").html("");
    $.ajax({
        url: urlcore + "/api/muser/admin/selectUserList?userType=" + userType + "&memberType=" + memberType + "&memberLevel=" + memberLevel + "&phone=" + phoneNumber + "&current=" + currentPage + "&startTime=" + $('#startTime').val() + "&endTime=" + $('#endTime').val(),
        type: "get",
        dataType: 'json',
//      jsonp:'jsonpCallback',//传递给后台程序，用来获取jsonp回调函数名的参数名  
         beforeSend: function(xhr) {
                xhr.withCredentials = true;
            },
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {
                callback(data.data);
                $("#pager").pager({
                    pagenumber: currentPage,
                    pagecount: data.data.pages,
                    totalcount: data.data.total,
                    buttonClickCallback: PageClick
                });

            } else{
                 alert(data.msg);
                 window.location.href="login.html";
            } 

        },error:function(data) {
        	
//			window.location.href="login.html";
		}
    });
}


var callback = function (data) {

    $.each(data.list, function (i, n) {

        var id = n.muser.id;
        var status = '';
        if (n.muser.mStatus == 1) {
            mstatus = '正常';
        } else if (n.muser.mStatus == 2) {
            mstatus = '封号';
        }

        var membertype = '';
        if (n.muser.memberType == 1) {
            membertype = '体验会员';
        } else if (n.muser.memberType == 2) {
            membertype = '彩虹会员';
        }

        //申请百夫长html
        var upgradeToCenturion = "";

        var usertype = '';
        if (n.muser.userType == 1) {
            usertype = '普通会员 ';
        } else if (n.muser.userType == 2) {
            usertype = '内部员工 ';
        } else if (n.muser.userType == 3) {
            usertype = '介绍人';
        } else if (n.muser.userType == 4) {
            usertype = '百夫长';
        } else if (n.muser.userType == 5) {
            usertype = '千夫长';
        } else if (n.muser.userType == 6) {
            usertype = '加盟商';
        } else if (n.muser.userType == 7) {
            usertype = '正在申请百夫长';
            upgradeToCenturion = '<a class="" name="升为百夫长" href="javascript:;" data-toggle="modal" data-target="#centurionModal" onclick="openUpgradeToCenturionModal(' + id + ',\'' + n.muser.realName + '\')"  >审核百夫长</a>&nbsp;';
        }

        var memberlevel = '';
        if (n.muser.memberLevel == 1) {
            memberlevel = 'vip1';
        } else if (n.muser.memberLevel == 2) {
            memberlevel = 'vip2';
        } else if (n.muser.memberLevel == 3) {
            memberlevel = 'vip3';
        } else if (n.muser.memberLevel == 4) {
            memberlevel = 'vip4';
        } else if (n.muser.memberLevel == 5) {
            memberlevel = 'vip5';
        }

        /*	var time=n.gmtDatetime;
            var time1=toString(time);*/
        if (n.muser.mStatus == 1 || n.muser.mStatus == 3) {
            var status = "禁用";
        } else if (n.muser.mStatus == 2) {
            var status = "启用";
        }
        var userName=""
        if(n.muser.userName==null){
        	userName="- -";
        }else{
        	userName=n.muser.userName;
        }

        var thislist =
            '<tr class="footable-even" style="display: table-row;">' +
            '<td class="footable-visible"><input type="checkbox" /></td>' +
            '<td class="footable-visible">' + '<a  class="btn"   href="muser1.html?id=' + n.muser.id + '">' + n.muser.id + '</a></td>' +
            '<td class="footable-visible">' + userName + '</td>' +
            '<td class="footable-visible">' + n.muser.phone + '</td>' +
            '<td class="footable-visible">' + usertype + '</td>' +
            '<td class="footable-visible">' + membertype + '</td>' +
            '<td class="footable-visible">' + '<a href="order_list.html?userName='+userName+'"> '+n.muser.purchaseFrequency + '</a></td>' +
            '<td class="footable-visible">' + n.totalMoney + '</td>' +
            '<td class="footable-visible">' + n.rebateDuobi + '</td>' +
            '<td class="footable-visible">' +'<a class=""  href="income.html?userId=' + n.muser.id + '"  >'+ n.income + '</a></td>' +
            '<td class="footable-visible">' + n.muser.mNumber + '</td>' +
            '<td class="footable-visible">' + new Date(n.muser.gmtDatetime).pattern("yyyy-MM-dd hh:mm:ss") + '</td>' +
            '<td class="footable-visible">' + mstatus + '</td>' +
            '<td class="footable-visible"><img width="40px" height="40px" src="' + n.muser.qrCode + '"></td>' +
            '<td class="footable-visible footable-last-column">' +upgradeToCenturion +
            '<a class=""  href="javascript:;" data-toggle="modal"   data-target="#chenge" onclick="store(' + id + ')" >删除</a>&nbsp;' +
            '<a class="" name="查看" href="javascript:;" onclick="findSubUser(' + id + ',' + n.muser.mNumber + ')"  >查看下级</a>&nbsp;' +
            '<a class="" name="变更身份" href="javascript:;" data-toggle="modal" data-target="#chenge2"  onclick="giveId(' + id + ')"  >变更身份</a>&nbsp;' +
            '<a class="" name="变更会员等级" href="javascript:;" data-toggle="modal" data-target="#chenge1"  onclick="giveId(' + id + ')"  >变更会员类型</a>&nbsp;' +
            '<a  class="" name="禁用" href="javascript:;"  onclick="thisDelete(' + id + ')">' + status + '</a>&nbsp;' +
            '<a  class=""  href="user_detail.html?id=' + id + '"  >详情</a></td>' +
            '</tr>';
        $('#thislist').append(thislist);
    });

}


PageClick = function (pageclickednumber) {
    var phoneNumber = $('#phoneNumber').val().trim();
    var userType=$("#userType").val();
    var memberType=$("#memberType").val();
    init(pageclickednumber, memberType, userType, phoneNumber, memberLevel, callback)
}


function EnterSearchList() {
    var code = event.keyCode;
    if (code == 13) {
        searchList();
    }

}

/**
 * 搜索
 */
function searchList() {

    var phoneNumber = $('#phoneNumber').val().trim();
    init(currentPage, memberType, userType, phoneNumber, memberLevel, callback)

}


function selectOrdersStatus1() {
    memberType = $('#memberType').val();
    init(currentPage, memberType, userType, phoneNumber, memberLevel, callback)

}

function selectOrdersStatus2(authstatus) {
     userType = $('#userType').val();
    init(currentPage, memberType, userType, phoneNumber, memberLevel, callback)

}

function selectOrdersStatus3(authstatus) {
    var memberLevel = $('#memberLevel').val();
    init(currentPage, memberType, userType, phoneNumber, memberLevel, callback)

}

//禁用或启用
function thisDelete(id) {

    $.ajax({
        url: urlcore + "/api/muser/disableOrEnable?id=" + id,
        type: "get",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            loadMyEssay('', '', '', '');
        },
        error: function () {
            /* Act on the event */
            alert("error");
        }
    });

}

/**
 * 删除会员
 * @param {Object} id
 */

/*function insertPwdNo(id) {
	var phone = $('#phone').val().trim();
 
	$.ajax({
		url: urlcore + "/api/muser/changeRecommend?oldId=" + id1 + "&phone=" + phone,
		type: "GET",
		dataType: 'json',
		contentType: "application/json;charset=utf-8",
		success: function(data) {
			if(data.success == true) {
				alert("移交成功!")
			} else {
				alert(data.msg);
			}

		},
		error: function() {
			alert("error");
		}
	});

}*/
/**
 * 删除会员
 * @param {Object} id
 */

function delMuser() {
    var password = $("#password").val();
    var userId = sessionStorage.getItem("userId");
    if (password == "") {
        alert("请输入密码");
        return;
    }
    $.ajax({
        url: urlcore + "/api/muser/delMuser?userId=" + userId + "&password=" + password,
        type: "GET",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {
                alert(data.msg)
            } else {
                alert(data.msg);
            }

        },
        error: function () {
            alert("error");
        }
    });

}

/**
 * 查看下级会员
 */
function findSubUser(id, num) {
    if (num == 0) {
        alert("该会员下尚未团队");
        return;
    }
    sessionStorage.setItem("id",id);
    sessionStorage.setItem("num",num);
    var currentPage=1; 
    findsubUserDateList(id,currentPage);

}

function findsubUserDateList(id,currentPage,num){
	 $("#thislist").html("");
	    $.ajax({
        url: urlcore + "/api/muser/selectUserTeamList?userId=" + id + "&current=" + currentPage,
        type: "GET",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {
            	$("#thiscount").html(num);
                callback(data.data);
                $("#pager").pager({
                    pagenumber: currentPage,
                    pagecount: data.data.pages,
                    totalcount: data.data.total,
                    buttonClickCallback: subUserPageClick
                });
            } else {
                alert(data.msg);
            }

        },
        error: function () {
            alert("error");
        }
    });
}

//查看下级分页
subUserPageClick = function (pageclickednumber) {
    var id=sessionStorage.getItem("id");
    var num=sessionStorage.getItem("num");
    findsubUserDateList(id,pageclickednumber,num)
}

function giveId(id, memberType2) {
    id1 = id;

}

function store(id) {
    sessionStorage.setItem("userId", id);
}

/**
 * 更改会员类型
 */
function chengeType1() {
    var memberType1 = $('#memberType1').val();

    $.ajax({
        url: urlcore + "/api/muser/chengeType1?id=" + id1 + "&memberType1=" + memberType1,
        type: "GET",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {
                alert("变更成功！");
                window.location.reload();
            } else {
                alert(data.msg);
            }

        },
        error: function () {
            alert("error");
        }
    });

}

//变更身份
function chengeType2() {
    var userType1 = $('#userType1').val();

    $.ajax({
        url: urlcore + "/api/muser/chengeType2?id=" + id1 + "&userType1=" + userType1,
        type: "GET",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {
                window.location.reload();
            } else {
                alert(data.msg);
            }

        },
        error: function () {
            alert("error");
        }
    });

}


function chengeType3() {
    var memberLevel1 = $('#memberLevel1').val();

    $.ajax({
        url: urlcore + "/api/muser/chengeType3?id=" + id1 + "&memberLevel1=" + memberLevel1,
        type: "GET",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        success: function (data) {
            if (data.success == true) {

            } else {
                alert(data.msg);
            }

        },
        error: function () {
            alert("error");
        }
    });

}

// 打开申请百夫长modal
function openUpgradeToCenturionModal(id, name) {
    sessionStorage.setItem("userId", id);
    $("#requireName").text(name);
}

/**
 * 升为百夫长 tag 1 为审核通过 2 为审核拒绝
 */
function upgradeToCenturion(tag) {
    var userType = "";
    // 审核通过
    if (tag == 1)
        userType = 4;
    // 审核拒绝
    if (tag == 2)
        userType = 1;
    var userId = sessionStorage.getItem("userId");
    var uptInfo = {
        id: userId,
        userType1: userType
    };
    $.ajax({
        url: urlcore + "/api/muser/chengeType2",
        type: "GET",
        dataType: 'json',
        contentType: "application/json;charset=utf-8",
        data:uptInfo,
        success: function (data) {
            if (data.success == true) {
                alert("操作成功");
                window.location.reload();
            } else {
                alert(data.msg);
            }

        },
        error: function () {
            alert("error");
        }
    });

}